const { mail: { service, user, pass } } = require('../config')
const nodemailer = require('nodemailer')
const htmlEmplate = {
  authCode(code) {
    return `<!DOCTYPE html><html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Flying Node</title><style>h1{margin-left:.5em}p{margin:8px;margin-left:1.5em}.code{margin:1em auto;text-align:center}code{font-size:20px;padding:6px;font-family:Consolas;border:1px solid #ccc}.tips{font-size:14px}</style></head><body><h1>欢迎注册FLYING NODE: JD</h1><p>这里是你的验证码，自发送后十分钟内有效。</p><p class="tips">! 重新发送验证码会使仍在有效期内的上一个验证码失效</p><p class="tips">如果不是本人操作，请无视</p><p class="code"><code>{{auth code}}</code></p></body></html>`
      .replace('{{auth code}}', code)
  }
}

let transporter = nodemailer.createTransport({
  service,
  port: 465,
  secureConnection: true,
  auth: {
    user,
    pass,
  },
});

module.exports = {
  /** * 发送邮件 */
  sendEmail(to, subject, html) {
    return new Promise((e, r) => {
      transporter.sendMail({
        from: user,
        to,
        subject,
        html
      }, (error, info) => {
        if (error) {
          console.log(error);
          r()
        } else {
          console.log('邮件发送成功')
          e(info)
        }
      });
    })
  },
  async sendAuthCode(to, code) {
    return await module.exports.sendEmail(to, 'NO.1 JD', htmlEmplate.authCode(code))
  }
}